﻿using System;
using System.ComponentModel;
using System.Linq;
using ProjectEuler.Linq;

namespace ProjectEuler.Problems
{
    [EulerProblem(14, 837799)]
    [Description("Find the longest sequence using a starting number under one million.")]
    internal sealed class Problem014 : EulerProblem
    {
        public override Object Solve()
        {
            Func<Int64, Int64> collatzLength = null;

            collatzLength = n =>
            {
                if (n > 1)
                {
                    return 1 + collatzLength((n.IsEven()) ? (n / 2) : (3 * n + 1));
                }

                return 1;
            };

            collatzLength = collatzLength.Memoize();

            return (1).To(1000000)
                    .Select(n => new { n, len = collatzLength(n) })
                    .WithMax(x => x.len)
                    .n;
        }
    }
}
